package com.atshiyou.servlet;

import com.atshiyou.webDatabase.ConnectMysql;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(value = "/regist")
public class RegistServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter printWriter = resp.getWriter();
        String registName = req.getParameter("registName");
        String registPasswd = req.getParameter("registPasswd");
        String registPasswd2 = req.getParameter("registPasswd2");
        if(registName==null || registPasswd==null || registPasswd2==null){
            printWriter.write("<script>alert('您的账号或者密码为空，请重新注册!');location.href='./regist.html'</script>");
            return;
        }
        if(!registPasswd.equals(registPasswd2)){
            printWriter.write("<script>alert('您输入的两次密码不一致，请重新注册!');location.href='./regist.html'</script>");
            return;
        }
        //验证用户名是否是重复的
        try {
            int point = ConnectMysql.findPoint(registName);
            if(point>0){//这里应该是重新写一个查询数据库的语句，不应该这样判断
                printWriter.write("<script>alert('用户名已注册，请换一个用户名重新注册!');location.href='./regist.html'</script>");
                return;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //验证通过之后，进行用户注册操作
        boolean b =false;
        try {
             b = ConnectMysql.insert(registName, registPasswd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(b){//注册成功，直接跳转到登录界面
            printWriter.write("<script>alert('恭喜您注册成功!点击确定跳转到登录界面');location.href='./index.jsp'</script>");
        }else{
            printWriter.write("<script>alert('系统故障，请重新注册');location.href='./regist.html'</script>");
        }


    }
}
